<?php

namespace app\company\model;


use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;

/**
 * @property int $id
 * @property int $company_id
 * @property int $goods_id
 * @property int $goods_cate_id 分类ID
 * @property string $descriptions 详情
 * @property  int $status 商品状态  1:上架,2:下架',
 * @property  int $racking_time 上架时间
 * @property  int $sold_out_time 下架时间
 */
class CompanyGoods extends Base
{

    public static function onBeforeInsert(CompanyGoods $model): void
    {
        $model->racking_time = time();
    }

    /**
     * @param CompanyGoods $model
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public static function onBeforeUpdate(CompanyGoods $model): void
    {

        $param = Request::param();

        //修改商品规格 此处只允许修改售价
        if (request()->param('specs', 0)) {
            foreach ($param['specs'] as $v) {
                if (!isset($v['money'])) exception('请填写修改后的价格');
                if (!$goodsRule = CompanyGoodsRule::where('company_id', $model->company_id)->where('id', $v['id'])->find())
                    exception('该规格还未引进,请先采购');
                $goodsRule->money = $v['money'];
                $goodsRule->save();
            }
        }

        //修改商品状态
        if (request()->param('status', 0)) {
            if ($param['status'] == 1) $model->racking_time = time();
            if ($param['status'] == 2) $model->sold_out_time = time();
            CompanyGoodsRule::where('company_id', $model->company_id)->where('goods_id', $model->id)->update(['status' => $param['status']]);
        }

        //修改费率 每次修改请求必需携带
        $rate = request()->only(['platform_rate', 'company_rate', 'driver_rate']);
        CompanyGoodsRate::where('company_id', $model->company_id)->where('goods_id', $model->goods_id)->update($rate);
    }
}